<template>
  <div class="error-boundary">
    <slot v-if="!hasError" />
    <div v-else class="error-fallback">
      <div class="error-icon">⚠️</div>
      <h3>出现了一些问题</h3>
      <p class="error-message">{{ errorMessage }}</p>
      <button @click="retry" class="retry-button">重试</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onErrorCaptured } from 'vue'

const hasError = ref(false)
const errorMessage = ref('')

onErrorCaptured((error) => {
  console.error('Vue组件错误:', error)
  hasError.value = true
  errorMessage.value = error.message || '未知错误'
  
  // 返回false阻止错误继续向上传播
  return false
})

function retry() {
  hasError.value = false
  errorMessage.value = ''
  // 重新渲染组件
  window.location.reload()
}
</script>

<style scoped>
.error-boundary {
  width: 100%;
  min-height: 200px;
}

.error-fallback {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  text-align: center;
}

.error-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.error-fallback h3 {
  color: #dc3545;
  margin-bottom: 0.5rem;
}

.error-message {
  color: #666;
  margin-bottom: 1rem;
  font-size: 0.9rem;
}

.retry-button {
  background: #007bff;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.retry-button:hover {
  background: #0056b3;
}
</style>